package com.woniu.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.woniu.constants.RedisConstants;
import com.woniu.constants.WeChatConstants;
import com.woniu.entity.SysConfig;
import com.woniu.entity.WechatExceptions;
import com.woniu.entity.WechatTemplateMessage;
import com.woniu.mapper.*;
import com.woniu.service.RedPacketPoolService;
import com.woniu.service.WechatService;
import com.woniu.utils.RedisUtil;
import com.woniu.utils.TimeUtil;
import com.woniu.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Description:
 * @Author: woniu
 * @date: 2024/1/11 14:09
 */
@Slf4j
@Component
@EnableScheduling
public class SubscriptionTask {

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private RedPacketPoolMapper redPacketPoolMapper;

    @Autowired
    private WechatTemplateMessageMapper wechatTemplateMessageMapper;

    @Autowired
    private NuserSubscriptionMapper nuserSubscriptionMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TransactionTemplate transactionTemplate;

    //@Scheduled(cron = "0 0/1 7-22 * * ? ")
    @Scheduled(cron = "0 30 7,16,20 * * ? ")
    public void redPacketSub() throws InterruptedException {

        WechatTemplateMessage wechatTemplateMessage = wechatTemplateMessageMapper.selectById(WeChatConstants.WECHAT_TEMPLATE_REDPACKET);
//        if (!wechatTemplateMessage.getSendStatus()){
//            return;
//        }

        // 先查询是否需要发送
//        String sendKey = RedisConstants.REDPACKET_SEND_PROGRAM;
//        boolean exists = redisUtil.exists(sendKey);
//        if (!exists){
//            log.info("识别不到rediskey:"+ exists +"|"+sendKey);
//            return;
//        }
//        // 删除红包通知
//        else {
//            log.info("识别到发红包通知了~");
//            redisUtil.delete(sendKey);
//        }
        // 今日初始时间
        String nowStartDate = TimeUtil.getNowStartDate();
        // 今日结束时间
        String nowEndDate = TimeUtil.getNowEndDate();


        // 查询订阅了消息且没中过红包的用户
        //List<UserOpenidVO> subUsers = nuserSubscriptionMapper.findSubUserByTempId(WeChatConstants.WECHAT_TEMPLATE_REDPACKET);
        List<UserOpenidVO> subUsers = nuserSubscriptionMapper.findSubUserAndNoRedPacketByTempId(WeChatConstants.WECHAT_TEMPLATE_REDPACKET,nowStartDate,nowEndDate);
        if (CollectionUtils.isEmpty(subUsers)){
            //subSendOff(wechatTemplateMessage);
            return;
        }


        // 查询系统配置
        SysConfig sysConfig = sysConfigMapper.selectOne(new LambdaQueryWrapper<SysConfig>()
                .orderByDesc(SysConfig::getUpdateTime)
                .last(" limit 1"));
        if (sysConfig == null){
            sysConfig = new SysConfig();
            sysConfig.setRedEinmalNumber(200);
        }



        for (UserOpenidVO subUser : subUsers) {

            // 有可能有空的
            if (ObjectUtil.isNull(subUser) || StringUtils.isEmpty(subUser.getNuserId()) || StringUtils.isEmpty(subUser.getOpenid())){
                continue;
            }

            // 查询用户今日是否已经中过红包
//            if (redPacketPoolMapper.existReceivedByNowDateAndUserId(nowStartDate,nowEndDate,subUser.getNuserId())){
//                return;
//            }

            // 查询用户是否已超过发送次数限制,每天最多5次，每2小时最多一次
            // 总次数redis key
            String wechatSubKey = RedisConstants.USER_PROGRAM_REDPACKET + subUser.getNuserId();
            // 两小时的redis key
            String wechatSubTwoHourKey = RedisConstants.USER_PROGRAM_REDPACKET_TWO_HOUR + subUser.getNuserId();

            // 两小时内是否已经下发过
            if (redisUtil.exists(wechatSubTwoHourKey)){
                continue;
            }

            // 是否超过3次
            String subNum = redisUtil.getString(wechatSubKey);
            if (!StringUtils.isEmpty(subNum) && Integer.parseInt(subNum) >= 3){
                continue;
            }

            HashMap<String, String> temMap = new HashMap<>();
            // 组装数据
            temMap.put("thing1", "热热闹闹过个年");
            temMap.put("time2",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(wechatTemplateMessage.getUpdateTime()));
            temMap.put("thing3", sysConfig.getRedEinmalNumber() + "个");
            // 发送订阅
            wechatService.pushMiniTemplateMessage(wechatTemplateMessage.getTempId(),temMap,subUser.getOpenid());
            // 总次数key存在，则自增1
            if (redisUtil.exists(wechatSubKey)) {
                redisUtil.setIncrement(wechatSubKey, (long) 1);
            } else {
                // 计算距离0点的结束时间
                Long timeLeft = TimeUtil.calculateTime();
                redisUtil.setString(wechatSubKey, timeLeft);
            }
            // 添加四小时key
            redisUtil.setString(wechatSubTwoHourKey, 14400000L);

        }


        // 关闭发送
        //subSendOff(wechatTemplateMessage);
        // 任务延迟2秒结束
        Thread.sleep(2000);

    }


    /**
     * 关闭发送
     * @param wechatTemplateMessage
     */
    private void subSendOff(WechatTemplateMessage wechatTemplateMessage) {
        wechatTemplateMessageMapper.update(null,new LambdaUpdateWrapper<WechatTemplateMessage>()
                .eq(WechatTemplateMessage::getId, wechatTemplateMessage.getId())
                .set(WechatTemplateMessage::getSendStatus,false));
    }

    /**
     * 组装数据和发送订阅消息
     * @param templateId 模板ID
     * @param temMap 发送内容
     * @param openId 用户openid
     */
/*    private void pushMiniTemplateMessage(String templateId, HashMap<String, String> temMap, String openId) {

        ProgramTemplateMessageVo programTemplateMessageVo = new ProgramTemplateMessageVo();
        programTemplateMessageVo.setTemplate_id(templateId);

        //组装关键字数据
        HashMap<String, SendProgramTemplateMessageItemVo> hashMap = new HashMap<>();
        temMap.forEach((key, value) -> hashMap.put(key, new SendProgramTemplateMessageItemVo(value)));

        programTemplateMessageVo.setData(hashMap);
        programTemplateMessageVo.setTouser(openId);

        // 发送订阅消息
        redisUtil.lPush(WeChatConstants.WE_CHAT_MESSAGE_KEY_PROGRAM, JSONObject.toJSONString(programTemplateMessageVo));
        //return wechatService.sendMiniSubscribeMessage(programTemplateMessageVo);
    }*/


}
